
import React, { PropsWithChildren, useEffect, useState } from 'react';
import { ModalForm, ProCard } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { PlusOutlined } from '@ant-design/icons';
import { Card, message, Upload } from 'antd';

interface UpdateFormProps {
  classCategoryEnum: Map<number, { text: string }>;
  children: any;
  echoRecord: API.StudentInfo;
}
const AssignForm: React.FC<PropsWithChildren<UpdateFormProps>> = ({
  children,
  echoRecord,
}) => {
  const { avateHandler } = useModel(
    'Student.model',
    (model) => ({
      avateHandler: model.avateHandler,
    }),
  );
 
  const [imgUrl, setImgUrl] = useState<string>('');
  const [file, setFile] = useState<File | null>(null);
   const [newAvatarResponse, setNewAvatarResponse] = useState<any | null>(null);
   
     useEffect(() => {
       // 初始化时设置已有图片的 URL
       if (echoRecord.stu_avatar) {
         setImgUrl(`http://localhost:3002${echoRecord.stu_avatar}`);
       }
     }, [echoRecord.stu_avatar]);
 
  const beforeUpload = (file: File) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
    if (!isJpgOrPng) {
      message.error('只能上传 .jpg 或 .png 文件');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('文件大小不能超过 2MB');
    }
    return isJpgOrPng && isLt2M;
  };

  const changeHandler = (info: any) => {
    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'done') {
      const newImgUrl = window.URL.createObjectURL(
        info.file.originFileObj as Blob,
      );
      setImgUrl(newImgUrl);
      console.log(newImgUrl);
      setFile(info.file.originFileObj);
    }
  };

const customRequest = async (options: any) => {
  const { onSuccess, onError, file } = options;
  const formData = new FormData();
  formData.append('avatar', file);

  try {
    const response = await fetch('/api/student/avatarupload', {
      method: 'POST',
      headers: {
        Authorization: sessionStorage.getItem('token') || '',
      },
      body: formData,
    });

    if (response.ok) {
      const data = await response.json();
      setNewAvatarResponse(data); // 存储上传返回的响应数据
      setImgUrl(`http://localhost:3002${data.data}`)
      onSuccess(data, file);
    } else {
      onError({ message: '上传失败' }, file);
    }
  } catch (error) {
    onError({ message: '网络错误' }, file);
  }
};

  return (
    <ModalForm
      trigger={children}
      autoFocusFirstInput
      initialValues={echoRecord}
      submitTimeout={2000}
      modalProps={{ destroyOnClose: true }}
      onFinish={async (values) => {
        if (!file) {
          message.error('请先选择要上传的图片');
          return false;
        }
        const formData = new FormData();
        formData.append('avatar', file);

        const success = await avateHandler({
          ...values,
          stu_id: echoRecord.stu_id,
          stu_avatar_old: echoRecord.stu_avatar || null,
          stu_avatar_new: newAvatarResponse.data,
        });
        return success;
      }}
    >
        <ProCard
          title="图片存档"
          bordered
          headerBordered
        >
          <ProCard colSpan="50%">
            <div
              style={{
                height: 360,
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
              }}
            >
              {imgUrl ? (
                <img
                  src={imgUrl}
                  alt="预览"
                  style={{ maxWidth: '100%', maxHeight: '100%' }}
                />
              ) : (
                <p>未选择图片</p>
              )}
            </div>
          </ProCard>
          <ProCard>
            <div
              style={{
                height: 360,
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
              }}
            >
              <Upload
                listType="picture"
                showUploadList={false}
                accept=".jpg,.png,.jpeg"
                beforeUpload={beforeUpload}
                onChange={changeHandler} // 上传图片时触发
                // action="/api/student/avatarupload"
                // name="avatar"
                // headers={{ Authorization: sessionStorage.getItem('token') }}
                customRequest={customRequest}
              >
                <Card>
                  <PlusOutlined />
                </Card>
              </Upload>
              <p>只能上传.jpg,.jpeg,.png文件，且大小不超过2MB</p>
            </div>
          </ProCard>
        </ProCard>
    </ModalForm>
  );
};

export default AssignForm;


